﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SQLite;
using System.Data;
using System.ComponentModel;
using PTCScheduler.UnitTests;

namespace PTCScheduler
{
    /// <summary>
    /// Interaction logic for MainWindow_Page.xaml
    /// </summary>
    public partial class MainWindow_Page : Page, ScheduleReport
    {
        //SQLite connection for the main window page
        private SQLiteConnection conn;

        //SQLite data dapter for main window page
        private SQLiteDataAdapter da;

        //SQLite database connection string
        private String connString = SystemQueries.dbConnString();

        //Selected date and time from the home calendar.
        private static DateTime selectedDateAndTime;

        //Background worker to handle sending reminder emails.
        private System.ComponentModel.BackgroundWorker backgroundWorkerReminderEmails = new System.ComponentModel.BackgroundWorker();

        //Constructor for mainwindow_page.
        public MainWindow_Page()
        {
            //Dynamically initalizes all GUI components
            //for the main window. 
            InitializeComponent();
            
            //Unit Testing
            //new ConferenceUnitTests();
            //new EmailAutomationUnitTests();
            //new SystemQueriesUnitTests();

            //Send reminder emails.
            ReminderEmails reminderEmails = new ReminderEmails();
            reminderEmails.sendReminderEmails();

            //Connect to database.
            dbConn();

            //Query the results and fill datagridview.
            queryResults();
        }

        /**Void method to handle the selected dates changed event from home Calendar.
         * When different date is selected the contents of the selected date textbox
         * is changed to the selected date.**/
        private void homeCalendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            //Set warning label contents to cannot schedule for past date.
            warninglbl.Content = "Cannot schedule for past date.";

            //If the selected scheduling date is after current date, then display date in textbox.
            //Otherwise user attempted to select a date that has passed and therefore conference
            //cannot be scheduled on that day.
            if (homeCalendar.SelectedDate >= System.DateTime.Today)
            {
                //Hide warning label.
                warninglbl.Visibility = Visibility.Hidden;

                //Change textbox contents to the date selected from the calendar.
                dateselectedtextBox.Text = ((DateTime)homeCalendar.SelectedDate).ToString("D");

                //Set selected date and time variable to selected date from homecalendar.
                selectedDateAndTime = (DateTime)homeCalendar.SelectedDate;
            }
            //If the date is not applicable, prompt user with message box.
            else
            {
                //Change textbox contents to empty.
                dateselectedtextBox.Text = "";

                //Display warning label prompting user date is unavailable.
                warninglbl.Visibility = Visibility.Visible;
            }
        }

        /**Schedule button click event to navigate from main page to 
         * new conference form page. MainWindow_Page.xaml --> NewConferenceForm_Page.xaml**/
        private void scheduleBtn_Click(object sender, RoutedEventArgs e)
        {
            //Set up system so that if the date textbox is empty then
            //system will not allow you to click the schedule button.
            if (dateselectedtextBox.Text == "")
            {
                //Set warning label to text to must select date.
                warninglbl.Content = "Must select a date on calendar.";

                //Show warning label
                warninglbl.Visibility = Visibility.Visible;
            }
            else
            {
                //Navigate to the new conference form page using the 
                //navigation service in order to allow for back tracking using
                //navigation buttons. 
                NavigationService.Navigate(new NewConferenceForm_Page());
            }
        }

        /**View by week menuitem click event to navigate from main page to
         * view by week page.**/
        private void viewbyweek_Click(object sender, RoutedEventArgs e)
        {
            //Navigate to the  view by week page using the 
            //navigation service in order to allow for back tracking using
            //navigation buttons.
            NavigationService.Navigate(new ViewBy_WeekPage());
        }

        /**View by student menuitem click event to navigate from main page to
         * view by student page.**/
        private void viewbystudent_Click(object sender, RoutedEventArgs e)
        {
            //Navigate to the view by student page using the 
            //navigation service in order to allow for back tracking using
            //navigation buttons.
            NavigationService.Navigate(new ViewBy_StudentPage());
        }

        /**View by teacher menuitem click event to navigate from main page to
         * view by teacher page.**/
        private void viewbyteacher_Click(object sender, RoutedEventArgs e)
        {
            //Navigate to the view by teacher page using the 
            //navigation service in order to allow for back tracking using
            //navigation buttons.
            NavigationService.Navigate(new ViewBy_TeacherPage());
        }

        //Connect to the database. 
        public void dbConn()
        {
            //Create connection.
            conn = new SQLiteConnection(connString);

            //Open connection
            conn.Open();
        }

        //Query the results and fill the datagrid.
        public void queryResults()
        {
            //Retrieve the today's query string from the SystemQueries class. 
            String sql = SystemQueries.todayQueryString();

            //Create dataset to fill with the results of the query. 
            DataSet ds = new DataSet(); //System.Data assembly

            //User SQLiteDataAdapter to retrieve results. 
            da = new SQLiteDataAdapter(sql, connString);

            //Fill the dataset with the results. 
            da.Fill(ds);

            //If there are no records then prompt user that there are no scheduled
            //conferences for today. Otherwise just display records. 
            if (ds.Tables[0].Rows.Count == 0)
            {
                noconferenceslbl.Visibility = Visibility.Visible;
            }
            else
            {
                noconferenceslbl.Visibility = Visibility.Hidden;
            }

            //Format the date and times using dtFormat.
            dtFormat(ds);

            //Display results in datagrid view. 
            dataGridMainWindow.ItemsSource = ds.Tables[0].DefaultView;

            //Close database connection.
            conn.Close();
        }

        //Method to format the date and time column
        private void dtFormat(DataSet ds)
        {
            //Iterate through each row and format accordinly
            foreach(DataRow row in ds.Tables[0].Rows)
            {
                //Create date time object
                DateTime dt = DateTime.Parse(row["Time"].ToString());
                //Set column equal to desired date pattern.
                row["Time"] = dt.ToString("hh:mm tt");
            }
        }

        //Method to retrieve the selected date and time for main window.
        public static DateTime mainSelectedDateAndTime()
        {
            //Return the selected date and time.
            return selectedDateAndTime;
        }

        //Handles Export Button Click Event.
        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            Console.WriteLine(dataGridMainWindow.Items.Count);
            //Prevent CSV from crashing system. 
            if (dataGridMainWindow.Items.Count > 0)
            {
                //Create new instance of CSVExport object which invokes the export to CSV method
                //to export data to excel worksheet.
                new CSVExport(dataGridMainWindow);
            }
        }

        //Handles Print Button Click Event.
        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            //Create new instance of the PrintDataGrid object which invokes the print feature
            //that prints contents of datagrid.
            new PrintDataGrid(dataGridMainWindow);
        }

        /**Navigate from main page to add new student using navigation service.**/
        private void NewStudent_Click(object sender, RoutedEventArgs e)
        {
            //Navigate to add student page when clicked.
            NavigationService.Navigate(new FileMenu_Pages.Add_StudentPage());
        }

        /**Navigate from main page to add new teacher using navigation service.**/
        private void NewTeacher_Click(object sender, RoutedEventArgs e)
        {
            //Navigate to add teacher page when clicked.
            NavigationService.Navigate(new FileMenu_Pages.Add_TeacherPage());
        }

        /**Navigate from main page to add new counselor using navigation service.**/
        private void NewCounselor_Click(object sender, RoutedEventArgs e)
        {
            //Navigate to add counselor page when clicked.
            NavigationService.Navigate(new FileMenu_Pages.Add_CounselorPage());
        }

        /**Close windows and exit application.**/
        private void Exit_Click(object sender, RoutedEventArgs e)
        {
            //Close application.
            Application.Current.Shutdown();
        }

        /**Navigate to update student page.**/
        private void UpdateStudent_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new EditMenu_Pages.UpdateStudent_Page());
        }

        /**Navigate to update teacher page.**/
        private void UpdateTeacher_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new EditMenu_Pages.UpdateTeacher_Page());
        }

        /**Navigate to update counselor page.**/
        private void UpdateCounselor_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new EditMenu_Pages.UpdateCounselor_Page());
        }

        /**Navigate to the update conference page.**/
        private void UpdateConference_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new EditMenu_Pages.UpdateConference_Page());
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        //Method to display the Help Window
        private void showHelpWindow()
        {
            HelpConfirmation help = new HelpConfirmation();
            help.Show();
        }

        //Handles the clicking event of the help icon menu item
        private void HelpMenu_Click(object sender, RoutedEventArgs e)
        {
            showHelpWindow();
        }

        
    }
}
